package com.example.controller;

import com.example.pojo.Announcement;
import com.example.pojo.Job;
import com.example.pojo.TakersJob;
import com.example.pojo.VO.JobWithTaker;
import com.example.service.AnnouncementService;
import com.example.service.LaborService;
import com.example.service.TakersJobService;
import com.example.util.ResponseWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/labor")
public class LaborController {

    @Autowired
    private LaborService laborService;

    @Autowired
    private AnnouncementService announcementService;

    @Autowired
    private TakersJobService takersJobService;


    @GetMapping("/works/{useridentityfer}")
    public ResponseWrapper<List<JobWithTaker>> getAllJob(@PathVariable int useridentityfer){
        List<Job> jobs = laborService.getAllJobsByUseridentityfer(useridentityfer);
        List<TakersJob> takersJobList = takersJobService.getTakeUsers(jobs);
        List<JobWithTaker> jobWithTakerList = new ArrayList<>();
        for (Job job: jobs){
            JobWithTaker jobWithTaker = new JobWithTaker();
            BeanUtils.copyProperties(job,jobWithTaker);
            jobWithTakerList.add(jobWithTaker);
        }
        for (JobWithTaker jobWithTaker : jobWithTakerList) {
            // 确保 takersName 初始化
            if (jobWithTaker.getTakersName() == null) {
                jobWithTaker.setTakersName(new ArrayList<>());
                jobWithTaker.setTakersId(new ArrayList<>());

            }
            for (TakersJob takersJob : takersJobList) {
                if (jobWithTaker.getId().equals(takersJob.getJobId())) {
                    jobWithTaker.getTakersName().add(takersJob.getUsername());
                    jobWithTaker.getTakersId().add(takersJob.getUserId());
                }
            }
        }
        System.out.println(jobWithTakerList);
        return ResponseWrapper.success(jobWithTakerList);
    }

    @GetMapping("/announcements/{month}")
    public ResponseWrapper<List<Announcement>> getAllAnnouncement(@PathVariable int month){
        List<Announcement> announcementList = announcementService.getAnnouncementListByMonth(month);
        return ResponseWrapper.success(announcementList);
    }

    @PostMapping("/addWork")
    public ResponseWrapper<Boolean> addJob(@RequestBody Job job){
        System.out.println("请求数据："+job);
        boolean isSuccess = laborService.insertJob(job);
        return ResponseWrapper.success(isSuccess);
    }
}
